package com.qiwx.pigeon.activity.manager;

import android.content.Intent;
import android.database.Cursor;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.ActionSheetUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.adapter.manager.WareHouseAdapter;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.BaseMVPActivity;
import com.qiwx.pigeon.data.params.QueryWareHouseParam;
import com.qiwx.pigeon.data.vo.WareHouseBean;
import com.qiwx.pigeon.eventbus.DbUpdateEvent;
import com.qiwx.pigeon.helper.DialogHelper;
import com.qiwx.pigeon.presenter.WareHousePresenter;
import com.qiwx.pigeon.viewinterface.IWareHouseView;
import com.qiwx.pigeon.widget.ArrowView;
import com.qiwx.pigeon.widget.itemderection.LineItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qiwx.pigeon.helper.DialogHelper.CODE_DELETE_CAGES;
import static com.qiwx.pigeon.helper.DialogHelper.CODE_DELETE_WAREHOUSE;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-24 14:59
 * 鸽仓管理
 **/
public class WareHouseManagerActivity extends BaseMVPActivity<IWareHouseView, WareHousePresenter> implements ISimpleDialogListener, IWareHouseView {
    @BindView(R.id.txt_warehouse_count)
    TextView txtWarehouseCount;
    @BindView(R.id.edt_number)
    EditText edtNumber;
    @BindView(R.id.txt_1)
    TextView txt1;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_return)
    ArrowView titleReturn;
    @BindView(R.id.txt_number)
    TextView txtNumber;
    List<WareHouseBean> data = new ArrayList<>();
    WareHouseAdapter adapter;
    List<String> options = new ArrayList<>();
    int currentwh_id;//当前操作id
    @BindView(R.id.txt_nodata)
    TextView txtNodata;

    @Override
    public WareHousePresenter createPresenter() {
        return new WareHousePresenter(new WeakReference<>(this));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_warehouse_manager;
    }

    @Override
    public void initAfterOnCreate() {
        titleReturn.changeArrowLeft();
        titleContent.setText("鸽仓管理");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.addItemDecoration(new LineItemDecoration(2));
        adapter = new WareHouseAdapter(R.layout.adapter_ware_house_item, data);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                goCageManager(data.get(position).getId());

            }
        });
        adapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                showActionSheet(position);
                return false;
            }
        });
        options.add("删除现有鸽仓");
        options.add("删除该鸽仓所有信息");

    }

    @Override
    protected void onResume() {
        super.onResume();
        queryWareHouses();
        //selectWareHouses();
    }

    private void queryWareHouses() {
//        HashMap<String, String> params = new HashMap<>();
//        params.put("userId", "1");
//        params.put("userName", "小明");
        QueryWareHouseParam param = new QueryWareHouseParam();
        param.setF_id(AppContext.getFarmId(this));
        mPresenter.getHouses(param);
    }

    public void sendDbUpdateEvent() {
        EventBus.getDefault().post(new DbUpdateEvent());
    }

    //删除鸽仓
    public void deleteWareHouse() {
        QueryWareHouseParam wareHouseParam = new QueryWareHouseParam();
        wareHouseParam.setWh_id(currentwh_id);
        wareHouseParam.setStatus(0);
        mPresenter.deleteHouse(wareHouseParam);

//        int rowsAffected = LitePal.delete(WareHouseModel.class, currentwh_id);
//        if (rowsAffected > 0) {
//            MyToast.showShort("删除鸽仓成功");
//            sendDbUpdateEvent();
//        } else {
//            MyToast.showShort("删除鸽仓失败");
//        }
    }

    //删除鸽仓所有信息
    public void deleteCages() {

        QueryWareHouseParam wareHouseParam = new QueryWareHouseParam();
        wareHouseParam.setWh_id(currentwh_id);
        wareHouseParam.setStatus(1);
        mPresenter.deleteHouse(wareHouseParam);
//        LitePal.where()
//        int rowsAffected = LitePal.deleteAll(CageModel.class, "wh_id=" + currentwh_id);
//        if (rowsAffected > 0) {
//            MyToast.showShort("删除鸽笼成功");
//            sendDbUpdateEvent();
//        } else {
//            MyToast.showShort("删除鸽笼失败");
//        }

    }

    public void showActionSheet(int pos) {
        currentwh_id = data.get(pos).getId();
        ActionSheetUtil.showSelectActionSheet(this, options, "取消", "鸽仓管理", new ActionSheetUtil.OnActionSheetOptionSelected() {
            @Override
            public void onSelected(String content) {
                if (options.get(0).equals(content)) {
                    //删除现有鸽仓
                    String info = "确定删除鸽仓?删除后鸽仓下的鸽笼也会删除";
                    DialogHelper.showCommonDialog(WareHouseManagerActivity.this, info, CODE_DELETE_WAREHOUSE);

                    //deleteWareHouse(currentwh_id);
                } else {
                    //删除鸽仓所有信息
                    String info = "确定删除鸽笼?";

                    DialogHelper.showCommonDialog(WareHouseManagerActivity.this, info, CODE_DELETE_CAGES);
                }
            }
        });
    }


    //去鸽笼管理
    public void goCageManager(int wh_id) {
        Intent go = new Intent(this, CageManagerActivity.class);
        go.putExtra("wh_id", wh_id);
        startActivity(go);
    }


    //添加仓库
    private void addWareHouse() {
        String num = edtNumber.getText().toString();
        if (TextUtils.isEmpty(num)) {
            MyToast.showCenterShort("编号不能为空");
            return;
        }
        QueryWareHouseParam param = new QueryWareHouseParam();
        param.setWh_number(Integer.parseInt(num));
        param.setF_id(AppContext.getEmployBean(this).getF_id());
        mPresenter.addHouse(param);

        //先查询仓库编号是否存在
//        if (LitePal.isExist(WareHouseModel.class, "number=?", num)) {
//            MyToast.showLong("该仓库编号已经存在，请填写其他编号");
//        } else {
//            WareHouseModel wareHouseModel = new WareHouseModel();
//            //wareHouseModel.setName("仓库" + num);
//            wareHouseModel.setUseStatus(1);
//            wareHouseModel.setNumber(Integer.valueOf(num));
////        wareHouseModel.setId(Integer.valueOf(num));
//            if (wareHouseModel.save()) {
//                edtNumber.setText("");
//                selectWareHouses();
//                sendDbUpdateEvent();
//            } else {
//                MyToast.showLong("添加鸽仓失败，检查鸽仓编号是否重复");
//            }
//        }

    }

    //查询仓库数量 表明就是类名，字段名就是属性名，小写
    private void selectWareHouses() {
        String sql = "select w.id as id,w.number as number ,w.usestatus as status,count(c.id) as count from warehousemodel as w left join cagemodel as c on w.id=c.wh_id group by w.id order by number";
        Cursor cursor = LitePal.findBySQL(sql);
        if (cursor != null) {
            data.clear();
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                int number = cursor.getInt(cursor.getColumnIndex("number"));
                int status = cursor.getInt(cursor.getColumnIndex("status"));
                int count = cursor.getInt(cursor.getColumnIndex("count"));
                WareHouseBean whb = new WareHouseBean();
                whb.setId(id);
                whb.setNumber(number);
                whb.setName(number + "");
                whb.setStatus(status);
                whb.setAmount(count);
                data.add(whb);
            }
            cursor.close();
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        txtWarehouseCount.setText(data.size() + "条");

    }

    @OnClick({R.id.txt_1, R.id.btn_add, R.id.title_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                addWareHouse();
//                loadData();
                break;
            case R.id.title_return:
                finish();
                break;
        }
    }

    @Override
    public void onQuerySuccess(List<WareHouseBean> result) {
        data.clear();
        data.addAll(result);
        adapter.notifyDataSetChanged();
        txtWarehouseCount.setText(data.size() + "条");
    }

    @Override
    public void onAddSuccess(WareHouseBean result) {
        MyToast.showLong("添加成功");
        queryWareHouses();

    }

    @Override
    public void onDeleteSuccess(WareHouseBean result) {
        MyToast.showLong("删除成功");
        queryWareHouses();
    }

    @Override
    public void onFailure(String error) {
        MyToast.showLong(error);
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {

    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {

    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        switch (requestCode) {
            case CODE_DELETE_WAREHOUSE:
                deleteWareHouse();
                break;
            case CODE_DELETE_CAGES:
                deleteCages();
                break;
        }

    }


}
